import i18n from '@/locale/i18n' // 假设你的 i18n 实例在这个路径（需根据实际项目调整）

// 全局请求封装
// const base_url = 'http://192.168.0.98:9998'
// const base_url = 'http://192.168.0.98:8889'
// const base_url = 'http://192.168.0.223:8080' // 旧地址(本地)
const base_url = 'http://192.168.0.98:9998' // 新地址
// const base_url = 'http://120.76.243.86:8881' // 公网
// const base_url = 'https://api-qa.dpltoy.com:8881' // 公网
const timeout = 60000 // 请求超时时间

// 登录接口路径（根据实际项目修改）
const LOGIN_URLS = [
	'/dpl/v1/auth/login/phone',
	'/dpl/v1/auth/login/email',
	'/dpl/v1/auth/register', // 可选：注册接口也不需要token
	'/dpl/v1/auth/refresh' // 可选：刷新token接口
]
// 封装 i18n 的 t 方法，避免重复代码
const t = (key) => i18n.global.t(key)
// console.log(123123, t('pleaselogin'));

// 防抖函数
const debounce = (fn, delay) => {
	let timer = null
	return function (...args) {
		if (timer) clearTimeout(timer)
		timer = setTimeout(() => {
			fn.apply(this, args)
		}, delay)
	}
}

const outLogin = () => {// 退出登录
	setTimeout(() => {
		uni.reLaunch({
			url: "/pages/login/login",
		})
	}, 1000)
	uni.setStorageSync('token', '')
	uni.setStorageSync('refreshToken', '')
	uni.setStorageSync('accessTokenExp', '')
	uni.setStorageSync('avatarUrl', '')
	uni.setStorageSync('username', '')
	uni.setStorageSync('userCode', '')
	uni.setStorageSync('dplID', '')
	uni.setStorageSync('userPhone', '')
}

const debouncedOutLogin = debounce(outLogin, 500)

// 请求封装
const request = (params) => {
	let url = params.url
	let method = params.method || "get"
	let data = params.data || {}

	// 判断是否为登录请求
	const isLoginRequest = LOGIN_URLS.some(loginUrl => url.startsWith(loginUrl))

	// 请求头
	let header = {
		'Content-Type': 'application/json;charset=UTF-8',
		...params.header
	}

	// 非登录请求添加 token
	if (!isLoginRequest) {
		header['Authorization'] = uni.getStorageSync('token')
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: data,
			timeout: timeout,
			success(response) {
				const res = response
				if (!res.data.code) return

				// token 过期处理（code: 997）
				if (res.data.code == 997) {
					try {
						let refreshToken = uni.getStorageSync('refreshToken')
						if (refreshToken) {
							uni.request({
								url: base_url + '/dpl/v2/auth/refreshToken',
								method: 'POST',
								header: header,
								data: { refreshToken: refreshToken },
								timeout: 10000
							}).then(res => {
								if (res.data.code == 200) {
									uni.setStorageSync('token', res.data.tokenList.accessToken)
									// 重新请求
									uni.request({
										url: base_url + url,
										method: method,
										header: {
											'Content-Type': 'application/json;charset=UTF-8',
											'Authorization': res.data.tokenList.accessToken
										},
										data: data,
										timeout: timeout,
										success: (retryRes) => resolve(retryRes.data),
										fail: (retryErr) => reject(retryErr)
									})
								} else {
									debouncedOutLogin()
								}
							}).catch(() => {
								debouncedOutLogin()
							})
						} else {
							debouncedOutLogin()
						}
					} catch (e) {
						debouncedOutLogin()
					}
				} else if (res.data.code == 981) {
					// show(res.data.msg)
				}

				// 成功响应（statusCode: 200）
				if (res.statusCode == 200) {
					resolve(res.data)
				} else {
					uni.clearStorageSync()
					switch (res.statusCode) {
						case 401:
							uni.showModal({
								title: t('prompt'), // 使用 i18n
								content: t('pleaselogin'), // 使用 i18n
								showCancel: false,
								success() {
									setTimeout(() => {
										uni.reLaunch({ url: "/pages/login/login" })
									}, 1000)
								}
							})
							break
						case 404:
							show(t('Therequestaddressdoesnotexist'))
							break
						case 500:
							show(t('Anerrorpleasetryagain'))
							console.error('服务器错误详情:', res.data)
							break
						default:
							show(t('Anerrorpleasetryagain'))
							break
					}
				}
			},
			fail(err) {
				// console.log('err', err)
				if (err.errMsg.indexOf('request:fail') !== -1) {
					show(t('networkanomaly'))
				} else {
					show(t('Anerrorpleasetryagain'))
				}
				reject(err)
			},
			complete() {
				uni.hideLoading()
				uni.hideToast()
			}
		})
	})
}
const show = (data) => {
	setTimeout(() => {
		// uni.showToast({
		// 	title: data, // 使用 i18n
		// 	icon: "error",
		// 	duration: 2000
		// })
		uni.showModal({
			title: t('prompt'),
			content: data,
			showCancel: false,
			success: function (res) {
				if (res.confirm) {

				}
			}
		});
	}, 100)
}
export default request